const express = require('express');
const cors = require('cors');
const fs = require('fs').promises;
const chokidar = require('chokidar');
const _ = require('lodash');
const app = express();
const PORT = 5677;

let messageQueue = [];
let lastChatData = [];

// 速率限制存储
const rateLimitStore = new Map();

// 清理过期记录的定时器
setInterval(() => {
    const now = Date.now();
    for (const [ip, { timestamp }] of rateLimitStore.entries()) {
        if (now - timestamp > 60000) { // 超过1分钟
            rateLimitStore.delete(ip);
        }
    }
}, 30000); // 每30秒清理一次

// 速率限制中间件
function rateLimiter(req, res, next) {
    const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
    const now = Date.now();
    
    if (!rateLimitStore.has(ip)) {
        rateLimitStore.set(ip, {
            count: 1,
            timestamp: now
        });
        return next();
    }
    
    const record = rateLimitStore.get(ip);
    
    if (now - record.timestamp > 60000) { // 超过1分钟，重置计数
        record.count = 1;
        record.timestamp = now;
        rateLimitStore.set(ip, record);
        return next();
    }
    
    if (record.count >= 10) { // 超过10次/分钟
        return res.status(429).json({
            status: 'error',
            error_code: 'RATE_LIMIT_EXCEEDED',
            message: '请求过于频繁，每分钟最多允许10次请求'
        });
    }
    
    // 增加计数
    record.count++;
    rateLimitStore.set(ip, record);
    next();
}

app.use(cors({
  origin: '*',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type']
}));

// 应用速率限制中间件到/poll端点
app.use('/poll', rateLimiter);

// 监视文件变化
const watcher = chokidar.watch('messages/public_chat.json', {
  persistent: true,
  ignoreInitial: true
});

watcher.on('change', async (path) => {
  try {
    const rawData = await fs.readFile(path, 'utf-8');
    const newChatData = JSON.parse(rawData);
    
    const newMessages = _.differenceWith(newChatData, lastChatData, _.isEqual);
    if (newMessages.length > 0) {
      const filteredMessages = newMessages.map(msg => ({
        user: msg.user,
        content: msg.content,
        timestamp: msg.timestamp
      }));
      messageQueue.push(...filteredMessages);
      lastChatData = newChatData;
    }
  } catch (err) {
    console.error('文件读取失败:', err);
  }
});

// 长轮询端点
app.get('/poll', async (req, res) => {
  if (messageQueue.length > 0) {
    const messages = messageQueue;
    messageQueue = [];
    return res.json(messages);
  }

  const timeout = setTimeout(() => {
    clearInterval(interval);
    res.status(204).end();
  }, 30000);
  
  const interval = setInterval(() => {
    if (messageQueue.length > 0) {
      clearTimeout(timeout);
      const messages = messageQueue;
      messageQueue = [];
      res.json(messages);
    }
  }, 1000);

  req.on('close', () => {
    clearInterval(interval);
    clearTimeout(timeout);
  });
});

// 初始化
fs.readFile('messages/public_chat.json', 'utf-8')
  .then(data => lastChatData = JSON.parse(data))
  .catch(err => console.error('初始化失败:', err));

app.listen(PORT, () => console.log(`服务运行在 http://localhost:${PORT}`));